package com.yizhuoyan.his.webapi.filter;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;
import java.util.Map;

/**
 * 使用Wrapper装配模式实现所有请求参数都进行trim
 * 如果参数为空白字符串，统一为null
 */
@WebFilter("/api/*")
@Slf4j
public class AllParameterTrimFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.debug("初始化{}",this.getClass().getName());
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        filterChain.doFilter(new HttpServletRequestWrapper((HttpServletRequest) servletRequest){
            @Override
            public String getParameter(String name) {
                String[] parameterValues = getParameterValues(name);
                return parameterValues!=null&&parameterValues.length>0?parameterValues[0]:null;
            }
            @Override
            public String[] getParameterValues(String name) {
                String[] parameterValues = super.getParameterValues(name);
                if(parameterValues==null){
                    return null;
                }
                for (int i = 0; i < parameterValues.length; i++) {
                    parameterValues[i]=trim(parameterValues[i]);
                }
                return parameterValues;
            }
            @Override
            public Map<String, String[]> getParameterMap() {
                Map<String, String[]> parameterMap = super.getParameterMap();
                parameterMap.replaceAll((k,v)->trim(v));
                return parameterMap;
            }
            private String[] trim(String[] arr){
                if(arr==null)return null;
                for (int i = arr.length;i-->0;arr[i]=trim(arr[i]));
                return arr;
            }
            private String trim(String s){
                return s==null||(s=s.trim()).length()==0?null:s;
            }
        },servletResponse);
    }
}
